/**
 *
 */
package pt.mleiria.app.web.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author manuel
 *
 */
public class LoginFilter implements Filter {

    @Resource
    private SessionContext sessionContext;

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpSession session = servletRequest.getSession(false);
        try {
            if (session != null && !session.isNew()) {
                chain.doFilter(request, response);
            } else {
                servletRequest.getSession(true);
                servletResponse.sendRedirect("/adaline");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try{
                servletRequest.getSession(false).invalidate();
            }catch(IllegalStateException ex){
                
            }
            servletResponse.sendRedirect("/adaline");
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
